package com.example.controller;

import com.example.Filter.MyFilter;
import com.example.dto.UserDto;
import com.example.service.UserService;
import com.example.service.impl.UserServiceimpl;
import com.mysql.cj.Session;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import lombok.Getter;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceimpl();
    @Getter
    public static HttpSession session;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserDto userDto = this.userService.login(username, password);

        session = req.getSession();

        session.setAttribute("user", userDto.getUser());
        Cookie JSESSIONID = new Cookie("JSESSIONID", req.getSession().getId());
        Cookie usernameCookie = new Cookie("username",username);
        Cookie passwordCookie = new Cookie("password",password);
        JSESSIONID.setMaxAge(60*60*24*7);
        usernameCookie.setMaxAge(60*60*24*7);
        passwordCookie.setMaxAge(60*60*24*7);
        resp.addCookie(JSESSIONID);
        resp.addCookie(usernameCookie);
        resp.addCookie(passwordCookie);

        if(userDto.getMsg().equals("登录成功")){
            req.getSession().setAttribute("user", userDto.getUser());
            resp.sendRedirect("/index.jsp");
        }else{
            req.setAttribute("Msg", userDto.getMsg());
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

}
